﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EncuentraloSilverlight.ServiceReference2;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using System.Collections;


namespace EncuentraloSilverlight
{
	public partial class User_View : Page
	{
        User usuario;
        List<string> Comunas;
       
		public User_View()
		{
            
			// Required to initialize variables
            
            InitializeComponent();
            Service2Client webservice = new Service2Client();
            webservice.FindUsersFromUsernameCompleted += (obj, eventarg) =>
                {
                    usuario = eventarg.Result[0];
                    this.TextBox_Name.Text = usuario.Name;
                    this.Label_email.Content = usuario.Name;
                    if (usuario.Addresses.Count > 0)
                    {
                        TextBox_AddressCiudad.Text = usuario.Addresses.First().City;
                        TextBox_AddressComuna.Text = usuario.Addresses.First().Commune;
                        TextBox_AddressNumber.Text = usuario.Addresses.First().Number;
                        TextBox_AddressCalle.Text = usuario.Addresses.First().Street;
                        
                    }
                    Comunas=LLenaComboBox_BuquedaPorComuna();

                    IEnumerable<Search> searchs = usuario.Searches.OrderByDescending(u => u.Date);
                    foreach (Search search in searchs)
                    {
                        listBox_search.Items.Add(search.Parameter + " " + search.Date.Value.ToShortDateString());   
                    }

                };

            webservice.FindUsersFromUsernameAsync(Cookie.GetCookie("EncuentraloUser"));                
		} 
      
          //Salir
        private void Button_Click_Salir(object sender, RoutedEventArgs e)
        {
            Cookie.SetCookie("EncuentraloUser", "");
            NavigationService.Navigate(new Uri("/Views/Home.xaml", UriKind.Relative));
        }
  
        private void KeyUp_TextBox_CommonExpressSearch(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Cookie.SetCookie("EncuentraloSearch", TextBox_CommonExpressSearch.Text);
                NavigationService.Navigate(new Uri("/Views/BusquedaExpress.xaml", UriKind.Relative));
            }
        }
        private void Click_Button_CommonExpressSearch(object sender, RoutedEventArgs e)
        {
            Cookie.SetCookie("EncuentraloSearch", TextBox_CommonExpressSearch.Text);
            NavigationService.Navigate(new Uri("/Views/BusquedaExpress.xaml", UriKind.Relative));
        }

        private void Button_EditarNombre_Click(object sender, RoutedEventArgs e)
        {
            Service2Client webservice = new Service2Client();
            if (TextBox_Name.Text.Length>0)
            {
                webservice.EditUserNameCompleted += (obj, eventarg) =>
                {
                    MessageBox.Show("Nombre editado correctamente");
                };
                webservice.EditUserNameAsync(usuario, TextBox_Name.Text);
            }

            else
            {
                MessageBox.Show("No se ha realizado modificación");
                TextBox_Name.Text=usuario.Name;
            }
        }
        private void Button_EditarDireccion_Click(object sender, RoutedEventArgs e)
        {

            Service2Client webservice = new Service2Client();
            if (TextBox_AddressCalle.Text != null && TextBox_AddressComuna.Text != null && TextBox_AddressCiudad.Text != null && TextBox_AddressNumber.Text != null)
            {

                webservice.EditUserAddressCompleted += (obj, eventarg) =>
                {
                    MessageBox.Show("Direccion editada con éxito");
                };

                Address new_address = new Address()
                {
                    City = TextBox_AddressCiudad.Text,
                    Commune = TextBox_AddressComuna.Text,
                    Street = TextBox_AddressCalle.Text,
                    Number = TextBox_AddressNumber.Text
                };

                webservice.EditUserAddressAsync(usuario, new_address);
            }
           
            else
            {
                MessageBox.Show("Su dirección no fue modificada por error en datos ingresados");
            }

        }
        private void Button_Buscar_Click(object sender, RoutedEventArgs e)
        {
            //si no hay parametro de busqueda se muestran todos los resultados
            if (ComboBox_Busquedas.SelectedIndex <0 && TextBox_Busqueda.Text.Length==0)
                Busqueda(4);             
            //Busqueda por nombre
            else if (ComboBox_Busquedas.SelectedIndex == 0)
                Busqueda(0);
            //Busqueda orden de precio
            else if (ComboBox_Busquedas.SelectedIndex == 1)
                Busqueda(1);
            //Busqueda en mi comuna
            else if (ComboBox_Busquedas.SelectedIndex == 2)
                Busqueda(2);
            //Busqueda por comuna
            else if (ComboBox_Busquedas.SelectedIndex == 3)
                Busqueda(3);

            if (ComboBox_Busquedas.SelectedIndex > -1 && ComboBox_Busquedas.SelectedIndex < 4)
            {
                Search search = new Search() { Date = DateTime.Now, Parameter = TextBox_Busqueda.Text, SearchType = ComboBox_Busquedas.SelectedIndex };
                Service2Client webservice = new Service2Client();
                if (search.Parameter.Length > 0)
                {
                    webservice.AddSearchfromUserAsync(usuario, search);

                    webservice.FindUsersFromUsernameCompleted += (obj, eventarg) =>
                    {
                        usuario = eventarg.Result[0];
                        
                        IEnumerable<Search> searchs = usuario.Searches.OrderByDescending(u => u.Date);
                        listBox_search.Items.Clear();
                        foreach (Search searchh in searchs)
                        {
                            listBox_search.Items.Add(searchh.Parameter + " " + searchh.Date.Value.ToShortDateString());
                        }

                    };

                    webservice.FindUsersFromUsernameAsync(Cookie.GetCookie("EncuentraloUser"));        
                }
            }
                        
        }
        private void Busqueda(int busqueda)
        {
            Service2Client webservice = new Service2Client();
            ObservableCollection<Product> products=null;
            //se buscan todos los resultados
            if (busqueda==4)
            {
                webservice.FindAllProductsCompleted += (obj, eventarg) =>
                {
                    products = eventarg.Result;

                    LinkProductSeller(products);
                };
                webservice.FindAllProductsAsync();

            }
            // Busca por nombre
            else if (busqueda == 0)
            {
                if (TextBox_Busqueda.Text.Length == 0)
                {

                    webservice.FindAllProductsCompleted += (obj, eventarg) =>
                    {
                        products = eventarg.Result;

                        LinkProductSeller(products);

                    };
                    webservice.FindAllProductsAsync();
                }
                else
                {
                    webservice.FindProductByNameCompleted += (obj, eventarg) =>
                    {
                        products = eventarg.Result;

                        LinkProductSeller(products);

                    };
                    webservice.FindProductByNameAsync(TextBox_Busqueda.Text);

                }                               
                              
            }
            //Orden de precio
            else if (busqueda == 1)
            {

                if (TextBox_Busqueda.Text.Length == 0)
                {
                    webservice.FindAllProductsCompleted += (obj, eventarg) =>
                    {
                        products = eventarg.Result;
                        products = OrdenarPorPrecio(products);
                        LinkProductSeller(products);

                    };
                    webservice.FindAllProductsAsync();
                }

                else
                {
                    webservice.FindProductByNameCompleted += (obj, eventarg) =>
                   {
                       products = eventarg.Result;
                       products = OrdenarPorPrecio(products);
                       LinkProductSeller(products);
                     
                   };
                    webservice.FindProductByNameAsync(TextBox_Busqueda.Text);

                 
                }


            }
             //por mi comuna
            else if (busqueda == 2)
            {
                products = new ObservableCollection<Product>();
                if (usuario.Addresses[0].Commune != null)
                {
                    webservice.GetAllSellersByCommuneCompleted += (obj, eventarg) =>
                        {
                            ObservableCollection<Seller> sellerByCommune = eventarg.Result;
                            foreach(Seller s in sellerByCommune)
                            {
                                
                               foreach(Product p in s.Products)
                               {
                                   if (TextBox_Busqueda.Text.Length == 0)
                                   {
                                       products.Add(p);
 
                                   }
                                     
                                   else if (p.Name.Equals(TextBox_Busqueda.Text, StringComparison.OrdinalIgnoreCase)||p.Name.Contains(TextBox_Busqueda.Text))
                                   {
                                       products.Add(p);
                                   }
                                   

                               }

                            }
                            
                            LinkProductSeller(products);

                            if (products== null)
                                MessageBox.Show("No hay resultados en su comuna");
 
                        };
                    webservice.GetAllSellersByCommuneAsync(usuario.Addresses[0].Commune);


                }
                else
                    MessageBox.Show("No tiene comuna registrada");

                

            }

            else if (busqueda == 3)
            {
                products = new ObservableCollection<Product>();
                if (ComboBox_BusquedasComunas.SelectedIndex>=0)
                {
                    webservice.GetAllSellersByCommuneCompleted += (obj, eventarg) =>
                    {
                        ObservableCollection<Seller> sellerByCommune = eventarg.Result;
                        foreach (Seller s in sellerByCommune)
                        {

                            foreach (Product p in s.Products)
                            {
                                if (TextBox_Busqueda.Text.Length == 0)
                                {
                                    products.Add(p);

                                }

                                else if (p.Name.Equals(TextBox_Busqueda.Text,StringComparison.OrdinalIgnoreCase)|| p.Name.ToLower().Contains(TextBox_Busqueda.Text.ToLower()))
                                {
                                    products.Add(p);
                                }


                            }

                        }

                        LinkProductSeller(products);

                        if (products == null)
                            MessageBox.Show("No hay resultados en su comuna");

                    };
                    webservice.GetAllSellersByCommuneAsync(Comunas.ElementAt(ComboBox_BusquedasComunas.SelectedIndex));


                }
                else
                    MessageBox.Show("No tiene comuna registrada");

                

           
                

 
            }
        }

        private void LinkProductSeller(ObservableCollection<Product> products)
        {
            List<DireccionDeVendedor> templist = new List<DireccionDeVendedor>();
            Service2Client webservice = new Service2Client();
            webservice.FindAllSellersCompleted += (objj, eventargg) =>
            {
                ObservableCollection<Seller> vendedores = eventargg.Result;

                foreach (Product prod in products)
                {
                    Seller seller = null;
                    foreach (Seller sell in vendedores)
                    {
                        if (sell.SellerID == prod.SellerID)
                        {
                            seller = sell;
                            break;
                        }
                    }

                    DireccionDeVendedor st = new DireccionDeVendedor() { Vendedor = seller.Name, Direccion = seller.Address.City + ", " + seller.Address.Commune + ", " + seller.Address.Street + " " + seller.Address.Number, Descripcion = prod.Description, Precio ="$"+ prod.Price.ToString(), Producto = prod.Name };
                    templist.Add(st);
                }
                DataGrid_ResultadoDeBusqueda.ItemsSource = templist;
            };

            webservice.FindAllSellersAsync();
        }
  
        private ObservableCollection<Product> OrdenarPorPrecio( ObservableCollection<Product> Desordenados ) 
        {
            Product Menor=new Product();
            ObservableCollection<Product> Ordenado= new ObservableCollection<Product>();
            //busco el precio mas bajo y lo pongo en la primera pos
            if (Desordenados != null)
            {
                while (Desordenados.Count > 0)
                {
                    Menor = Desordenados[0];
                    foreach (Product d in Desordenados)
                    {
                        if (Menor.Price >= d.Price)
                        {
                            Menor = d;
                        }
                    }
                    Ordenado.Add(Menor);
                    Desordenados.Remove(Menor);
                }
                return Ordenado;
            }

            else
                return null;
        }

        private string CommuneSelected(int selected)
        {
            string commune = Comunas.ElementAt(selected);
            return commune;
        }
        private List<string> LLenaComboBox_BuquedaPorComuna()
        {

            Service2Client webservice = new Service2Client();
            ObservableCollection<string> ListaDeComunas = new ObservableCollection<string>();
            webservice.GetAllCommunesBySellersCompleted += (obj, eventarg) =>
                {
                    ListaDeComunas = eventarg.Result;

                    for (int k=0; k<ListaDeComunas.Count(); k++)
                    {
                       
                        for (int i =k + 1; i < ListaDeComunas.Count; i++)
                        {                           
                            if (ListaDeComunas.ElementAt(k).Equals(ListaDeComunas[i], StringComparison.OrdinalIgnoreCase))
                            {

                                ListaDeComunas.RemoveAt(i);

                            }
                        }
                    }
                 
                    if (ListaDeComunas.Count > 0)
                    {
                        ComboBox_BusquedasComunas.ItemsSource = ListaDeComunas;
                        Comunas = ListaDeComunas.ToList();
           
                    }
                    
                };
            webservice.GetAllCommunesBySellersAsync();

         
            
            return ListaDeComunas.ToList();
           
        }

        private void ComboBox_Busquedas_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ComboBox_Busquedas.SelectedIndex == 3)
            {
                label_comunas.Visibility = Visibility.Visible;
                ComboBox_BusquedasComunas.Visibility = Visibility.Visible;
            }
            else
            {
                label_comunas.Visibility = Visibility.Collapsed;
                ComboBox_BusquedasComunas.Visibility = Visibility.Collapsed;
            }
        }
              
	}

    public class DireccionDeVendedor
    {

        public string Producto { get; set; }
        public string Precio { get; set; }
        public string Descripcion { get; set; }
        public string Vendedor { get; set; }
        public string Direccion { get; set; }    

            

    }

       
}